﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Newtonsoft.Json;

namespace GwLib.JqGridMvc
{
    public static class SerializationUtility
    {
        public static string SerializeToXml(object objectToSerialize)
        {
            MemoryStream mem = new MemoryStream();
            XmlSerializer ser = new XmlSerializer(objectToSerialize.GetType());
            ser.Serialize(mem, objectToSerialize);
            UTF8Encoding ascii = new UTF8Encoding();
            return ascii.GetString(mem.ToArray());
        }

        public static T DeserializeFromXml<T>(string xmlString)
        {
            return (T)DeserializeFromXml(typeof(T), xmlString);
        }

        public static object DeserializeFromXml(Type typeToDeserialize, string xmlString)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(xmlString);
            MemoryStream mem = new MemoryStream(bytes);
            XmlSerializer ser = new XmlSerializer(typeToDeserialize);
            return ser.Deserialize(mem);
        }

        public static string SerializeToJson(object objectToSerialize)
        {
            return JsonConvert.SerializeObject(objectToSerialize);
        }

        public static T DeserializeFromJson<T>(string jsonString)
        {
            return JsonConvert.DeserializeObject<T>(jsonString);
        }

        public static object DeserializeFromJson(Type typeToDeserialize, string jsonString)
        {
            return JsonConvert.DeserializeObject(jsonString, typeToDeserialize);
        }
    }
}
